package Servlet;

import Dto.ArticleDTO;
import Service.ArticleService;
import Service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Article;
import entity.User;
import exception.BusinessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONObject;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/4/30 23:45
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/articles/*")
public class ArticleServlet extends HttpServlet {
    private ArticleService articleService;
    private ObjectMapper objectMapper;

    @Override
    public void init() throws ServletException {
        try {
            Connection connection = DBUtil.getConnection();
            this.articleService = new ArticleService(connection);
            this.objectMapper = new ObjectMapper();
        } catch (SQLException e) {
            throw new ServletException("初始化数据库连接失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 统一设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        JSONObject responseJson = new JSONObject();

        try {
            // 检查登录状态
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            User user = (User) session.getAttribute("user");

            // 解析 multipart/form-data 请求
            if (!ServletFileUpload.isMultipartContent(req)) {
                responseJson.put("code", 400);
                responseJson.put("message", "请求必须为 multipart/form-data");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 解析请求
            List<FileItem> items = upload.parseRequest(req);
            String knowledgeBaseIdStr = null;
            String title = null;
            String content = null;
            List<FileItem> fileItems = new ArrayList<>();
            String method = null;
            Integer id = null;
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 普通表单字段
                    switch (item.getFieldName()) {
                        case "knowledgeBaseId":
                            knowledgeBaseIdStr = item.getString("UTF-8");
                            break;
                        case "title":
                            title = item.getString("UTF-8");
                            break;
                        case "content":
                            content = item.getString("UTF-8");
                            break;
                        case "id":
                            id = Integer.valueOf(item.getString("UTF-8"));
                        case "method":
                            method = item.getString("UTF-8");
                    }
                } else {
                    // 文件上传字段
                    if (!item.getName().isEmpty()) {
                        fileItems.add(item);
                    }
                }
            }

            // 验证必填字段
            if (knowledgeBaseIdStr == null || title == null || content == null || method == null) {
                responseJson.put("code", 400);
                responseJson.put("message", "缺少必要参数");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            int knowledgeBaseId = Integer.parseInt(knowledgeBaseIdStr);
            Article article = null;
            //判断是创建文章还是编辑文章
            if(method.equals("create")){
                // 创建文章
                article = articleService.createArticle(
                        knowledgeBaseId,
                        user.getUserId(),
                        title,
                        content,
                        fileItems
                );
                responseJson.put("code", 200);
                responseJson.put("message", "创建成功");
            }else{
                // 编辑文章
                if (id == null) {
                    responseJson.put("code", 400);
                    responseJson.put("message", "缺少必要参数");
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                article = articleService.updateArticle(
                        id,
                        knowledgeBaseId,
                        user.getUserId(),
                        title,
                        content,
                        fileItems
                );
                responseJson.put("code", 200);
                responseJson.put("message", "修改成功");
            }

            responseJson.put("data", new JSONObject(objectMapper.writeValueAsString(article)));

        } catch (NumberFormatException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "知识库ID格式错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (BusinessException e) {
            responseJson.put("code", 403);
            responseJson.put("message", e.getMessage());
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统内部错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } catch (Exception e) {
            responseJson.put("code", 500);
            responseJson.put("message", "处理请求时发生错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 设置编码
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        JSONObject responseJson = new JSONObject();

        try {
            // 检查登录状态
            System.out.println("进入查看所有文章方法");
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            User user = (User) session.getAttribute("user");

            String pathInfo = req.getPathInfo();
            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取知识库ID参数
                String knowledgeBaseIdStr = req.getParameter("knowledgeBaseId");
                if (knowledgeBaseIdStr == null) {
                    //查看全部知识库下公开的文章（其他用户公开、用户自身全部）
                    List<ArticleDTO> allArticles = articleService.getAllArticles(user.getUserId());
                    System.out.println( "allArticles:" + allArticles);
                    responseJson.put("code", 200);
                    responseJson.put("data", new JSONArray(objectMapper.writeValueAsString(allArticles)));
                }else{
                    int knowledgeBaseId = Integer.parseInt(knowledgeBaseIdStr);
                    List<Article> articles = articleService.getArticlesByKnowledgeBase(knowledgeBaseId, user.getUserId());
                    responseJson.put("code", 200);
                    responseJson.put("data", new JSONArray(objectMapper.writeValueAsString(articles)));
                }
            } else {
                // 获取单个文章
                String[] parts = pathInfo.split("/");
                if (parts.length != 2) {
                    responseJson.put("code", 400);
                    responseJson.put("message", "无效的URL格式");
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }

                int articleId = Integer.parseInt(parts[1]);
                Article article = articleService.getArticleWithPermissions(articleId, user.getUserId());

                responseJson.put("code", 200);
                responseJson.put("data", new JSONObject(objectMapper.writeValueAsString(article)));
            }

        } catch (NumberFormatException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "ID格式错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (BusinessException e) {
            responseJson.put("code", 403);
            responseJson.put("message", e.getMessage());
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统内部错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

}
